<?php

namespace App\Services\WxMaterial;

use App\Models\WxMaterial;
use App\Services\EasyWechat;
use App\Services\SysFileService;
use App\Services\WxErrorService;

/**
 * 图文素材业务逻辑
 * @package App\Services\WxMaterial
 */
class WxMaterialThumb implements WxMaterialInterface
{
    /**
     * 保存素材数据
     * @param $data
     */
    public function save($data)
    {
        if (!isset($data['is_forever']) || !in_array($data['is_forever'], [0, 1])) {
            throw new \Exception('请指定素材是否为永久素材');
        }
        if (empty($data['title'])) {
            throw new \Exception('请输入缩略图标题');
        }
        if (empty($data['view_url'])) {
            throw new \Exception('请提供缩略图地址');
        }
        $materialModel = WxMaterial::where('view_url', $data['view_url'])->first();
        if (empty($materialModel)) {
            \DB::beginTransaction();
            try {
                $materialModel = new WxMaterial;
                $materialModel->cat_id = $data['cat_id'] ?? 0;
                $materialModel->type = 'thumb';

                $materialModel->title = $data['title'];
                $materialModel->description = $data['description'] ?? '';
                //素材本地文件
                $materialModel->view_url = $data['view_url'];
                $localFileInfo = (new SysFileService())->getLocalFileInfoByRemoteUrl($data['view_url']);
                $materialModel->file_id = $localFileInfo['file_id'];
                $materialModel->is_forever = $data['is_forever'];

                if (empty($data['media_id'])) {
                    //上传到微信素材
                    $app = \App\Services\EasyWechat::officialAccount();
                    if ($materialModel->is_forever) {//永久
                        //压缩图片
                        $localFilePathInfo = pathinfo($localFileInfo['local_file_path']);
                        $thumbFilePath = $localFilePathInfo['dirname'] . '/' . $localFilePathInfo['filename'] . '_thumb.' . $localFilePathInfo['extension'];
                        if (!file_exists($thumbFilePath)) {
                            $img = \Image::make($localFileInfo['local_file_path'])->resize(900, 600, function ($constraint) {
                                $constraint->aspectRatio();
                            });
                            $img->save($thumbFilePath, 60);
                            $thumbFilePath = $img->basePath();
                        }
                        $apiRs = $app->material->uploadThumb($thumbFilePath);
                        //检查微信接口错误
                        WxErrorService::checkApiResponse($apiRs);
                        //微信端主表保存
                        $materialModel->media_id = $apiRs['media_id'];
                        $materialModel->wx_view_url = $apiRs['url'] ?? '';
                    } else {//临时
                        //压缩图片
                        $localFilePathInfo = pathinfo($localFileInfo['local_file_path']);
                        $thumbFilePath = $localFilePathInfo['dirname'] . '/' . $localFilePathInfo['filename'] . '_thumb.' . $localFilePathInfo['extension'];
                        if (!file_exists($thumbFilePath)) {
                            $img = \Image::make($localFileInfo['local_file_path'])->resize(200, 200, function ($constraint) {
                                $constraint->aspectRatio();
                            });
                            $img->save($thumbFilePath, 80);
                            $thumbFilePath = $img->basePath();
                        }
                        $apiRs = $app->media->uploadThumb($thumbFilePath);
                        //检查微信接口错误
                        WxErrorService::checkApiResponse($apiRs);
                        $materialModel->media_id = $apiRs['thumb_media_id'];
                        $materialModel->expire_time = $apiRs['created_at'] + 86400 * 3;
                    }
                } else {
                    $materialModel->media_id = $data['media_id'];
                    if ($materialModel->is_forever) {//永久
                        $materialModel->wx_view_url = $data['wx_view_url'] ?? '';
                    } else {
                        $materialModel->expire_time = time() + 86400 * 3;
                    }
                }

                $materialModel->preview_data = [
                    'title' => $data['title'],
                    'view_url' => $data['view_url'],
                ];
                $materialModel->save();
                \DB::commit();
            } catch (\Exception $e) {
                \DB::rollBack();
                throw new \Exception($e->getMessage());
            }
            return $materialModel->toArray();
        } else {
            if (empty($data['media_id'])) {
                //上传到微信素材
                $app = \App\Services\EasyWechat::officialAccount();
                //临时素材更新mediaId
                if ($materialModel->is_forever == 0 && strtotime($materialModel->expire_time) <= time()) {
                    //素材本地文件
                    $localFileInfo = (new SysFileService())->getLocalFileInfoByRemoteUrl($materialModel->view_url);
                    //重新上传临时素材
                    $apiRs = $app->media->uploadThumb($localFileInfo['local_file_path']);
                    //检查微信接口错误
                    WxErrorService::checkApiResponse($apiRs);
                    $materialModel->media_id = $apiRs['media_id'];
                    $materialModel->expire_time = $apiRs['created_at'] + 86400 * 3;
                    $materialModel->save();
                }
                //永久素材
                if ($materialModel->is_forever == 1 && empty($materialModel->media_id)) {
                    //素材本地文件
                    $localFileInfo = (new SysFileService())->getLocalFileInfoByRemoteUrl($materialModel->view_url);
                    $apiRs = $app->material->uploadThumb($localFileInfo['local_file_path']);
                    //检查微信接口错误
                    WxErrorService::checkApiResponse($apiRs);
                    $materialModel->media_id = $apiRs['media_id'];
                    $materialModel->expire_time = null;
                    $materialModel->save();
                }
            } else {
                $materialModel->media_id = $data['media_id'];
                if ($materialModel->is_forever) {//永久
                    $materialModel->wx_view_url = $data['wx_view_url'] ?? '';
                } else {
                    $materialModel->expire_time = time() + 86400 * 3;
                }
            }
            return $materialModel->toArray();
        }
    }

    /**
     * 删除素材
     * @param $materialId
     */
    public function del($materialId)
    {
        $findMaterial = WxMaterial::findOrFail($materialId);
        \DB::beginTransaction();
        try {
            //永久素材需要调用接口删除
            if (!empty($findMaterial->media_id)) {
                $app = EasyWechat::officialAccount();
                if ($findMaterial->is_forever) {
                    $apiRs = $app->material->delete($findMaterial->media_id);
                    WxErrorService::checkApiResponse($apiRs);
                }
            }
            $findMaterial->media_id = '';
            $findMaterial->expire_time = null;
            $findMaterial->save();
            $findMaterial->delete();
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 获取被动回复数据
     * @param $materialId
     */
    public function getPassiveReplyData($materialId)
    {
        $mediaId = $this->getMediaId($materialId);
        if ($mediaId) {
            return new Image($mediaId);
        } else {
            return '';
        }
    }

    /**
     * 获取微信mediaId（临时素材和永久素材处理方式不一样）
     * @param $materialId 素材主键ID
     * @param $reUpload 是否重新上传
     * @return string 素材media_id
     */
    public function getMediaId($materialId, $reUpload = false)
    {
        $findMaterial = WxMaterial::findOrFail($materialId);
        $findMaterial->push_result = '';
        //上传到微信素材
        $app = \App\Services\EasyWechat::officialAccount();
        //临时素材更新mediaId
        if ($findMaterial->is_forever == 0 && (empty($findMaterial->media_id) || strtotime($findMaterial->expire_time) <= time())) {
            //素材本地文件
            $localFileInfo = (new SysFileService())->getLocalFileInfoByRemoteUrl($findMaterial->view_url);
            //重新上传临时素材
            $apiRs = $app->media->uploadThumb($localFileInfo['local_file_path']);
            //检查微信接口错误
            try {
                WxErrorService::checkApiResponse($apiRs);
                $findMaterial->media_id = $apiRs['media_id'];
                $findMaterial->wx_view_url = $apiRs['url'] ?? '';
                $findMaterial->expire_time = $apiRs['created_at'] + 86400 * 3;
            } catch (\Exception $e) {
                $findMaterial->push_result = $e->getMessage();
            }
            $findMaterial->push_time = time();
            $findMaterial->save();
        }
        //永久素材
        if ($findMaterial->is_forever == 1 && empty($findMaterial->media_id)) {
            //素材本地文件
            $localFileInfo = (new SysFileService())->getLocalFileInfoByRemoteUrl($findMaterial->view_url);
            $apiRs = $app->material->uploadThumb($localFileInfo['local_file_path']);
            //检查微信接口错误
            try {
                WxErrorService::checkApiResponse($apiRs);
                $findMaterial->media_id = $apiRs['media_id'];
                $findMaterial->wx_view_url = $apiRs['url'] ?? '';
                $findMaterial->expire_time = null;
            } catch (\Exception $e) {
                $findMaterial->push_result = $e->getMessage();
            }
            $findMaterial->push_time = time();
            $findMaterial->save();
        }
        return $findMaterial->media_id;
    }

    /**
     * 获取群发素材ID
     * @param $materialId
     * @param $reUpload
     */
    public function getMassMediaId($materialId, $reUpload = false)
    {
        throw new \Exception('不支持获取群发素材ID');
    }

    /**
     * 下载单个素材ID内容到本地（此处和图片素材获取方式一致）
     * @param $mediaId
     */
    public function downloadMediaId($mediaId, $isForever = true)
    {
        $findMaterial = WxMaterial::where('media_id', $mediaId)->select('material_id', 'title', 'description', 'file_id', 'view_url')->first();
        if (empty($findMaterial)) {
            $findMaterial = new WxMaterial;
            //首先下载到本地目录
            $app = EasyWechat::officialAccount();
            if ($isForever) {
                $apiRs = $app->media->get($mediaId);
            } else {
                $apiRs = $app->material->get($mediaId);
            }
            WxErrorService::checkApiResponse($apiRs);
            //相对目录
            $savePath = 'upload' . DIRECTORY_SEPARATOR . date('Ymd');
            //绝对路径
            $saveRealPath = \Storage::disk('local')->path($savePath);
            $saveFileName = date("YmdHis") . uniqid();
            //保存到本地
            $newFileName = $apiRs->saveAs($saveRealPath, $saveFileName);
            $fileExt = pathinfo($newFileName, PATHINFO_EXTENSION);
            $fileExt || $fileExt = 'jpg';
            $fileInfo = [
                'disk_name' => 'sfy',
                'origin_name' => 'thumb.' . $fileExt,//原始文件名
                'file_ext' => $fileExt,//扩展名
                'file_size' => 0,//文件大小
                'file_type' => 'image',//文件类别
                'new_name' => $newFileName,
            ];
            $fileInfo['file_path'] = $savePath . DIRECTORY_SEPARATOR . $newFileName;
            //文件真实路径
            $disk = \Storage::disk($fileInfo['disk_name']);
            $disk->put($fileInfo['file_path'], \File::get($saveRealPath . '.' . $newFileName));
            //文件大小
            $uploadInfo = (new SysFileService())->uploadFile($fileInfo['file_path'], $fileInfo['origin_name']);
            $fileInfo['view_url'] = $uploadInfo['url'];
            $fileInfo['file_size'] = $uploadInfo['size'];
            $sysFile = (new SysFileService())->saveFileInfo($fileInfo);
            //保存到本地素材主表
            //微信端主表保存
            $findMaterial->cat_id = 0;
            $findMaterial->type = 'thumb';

            $findMaterial->title = '微信端封面图素材';
            $findMaterial->media_id = $apiRs['media_id'];
            $findMaterial->preview_data = [
                'title' => '微信端封面图素材',
                'view_url' => $fileInfo['view_url'],
            ];
            $findMaterial->file_id = $sysFile->file_id;
            $findMaterial->view_url = $fileInfo['view_url'];
            $findMaterial->is_forever = (int)$isForever;
            $findMaterial->save();
        }
        return $findMaterial->toArray();
    }

    /**
     * 同步线上数据到本地数据
     */
    public function sync()
    {
        return (new WxMaterialImage())->sync();
    }
}